import json
import logging

from django.http import JsonResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.utils.baseconv import base64
from django.utils.decorators import method_decorator
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from common.custom_exceptions import decorator_exception
from common.models import MusicInfo
from common.views import BaseListView, AuthTemplateView, get_obj, AuthShopAPIView, AuthMobileTemplateView
from groupshopping.models import GroupShopping, ShoppingModel, ShoppingGroup, ShoppingMem
from groupshopping.serializers import GroupShoppingSerializer, ShoppingModelSerializer

logger = logging.getLogger('qixiaobao')


class GroupShoppingListView(BaseListView):
    """活动列表"""
    template_name = 'groupshopping/list.html'
    model = GroupShopping
    context_object_name = "groupshopping_list"

    def get_queryset(self):
        self.keyword = self.request.GET.get('keyword', '')
        # 测试错误邮件
        # raise Exception('测似错误邮件')
        if self.keyword:
            self.keyword = self.keyword.replace('-', '+').replace('_', '/')
            self.keyword = (base64.decodestring(self.keyword)).strip()
        return GroupShopping.objects.filter(title__contains=self.keyword, shop=self.shop,
                                            status=GroupShopping.STATUS_VALID)

    def get_context_data(self, **kwargs):
        kwargs['secure'] = self.request.is_secure()
        return super(GroupShoppingListView, self).get_context_data(**kwargs)


class GroupShoppingAddView(AuthTemplateView):
    """新建活动"""
    template_name = 'groupshopping/add.html'
    serializer_class = GroupShoppingSerializer

    def get_context_data(self, **kwargs):
        kwargs['secure'] = self.request.is_secure()
        kwargs['musics'] = MusicInfo.objects.filter(status=MusicInfo.STATUS_VALID)
        return super(GroupShoppingAddView, self).get_context_data(**kwargs)

    def post(self, request, *args, **kwargs):
        serializer = GroupShoppingSerializer(data=request.POST)
        if serializer.is_valid():
            groupshopping = serializer.save(shop_id=kwargs['shop_id'], status=GroupShopping.STATUS_VALID)
            shopping_models = json.loads(request.POST['models'])
            models_serializer = ShoppingModelSerializer(data=shopping_models, many=True)
            if models_serializer.is_valid():
                models_serializer.save(info_id=groupshopping.id, status=ShoppingModel.STATUS_VALID)
            return JsonResponse({'status': 0, 'detail': 'success'})
        else:
            return JsonResponse({'status': 1, 'detail': '活动添加失败！', 'errors': serializer.errors})


class GroupShoppingEditView(AuthTemplateView):
    """编辑活动"""
    template_name = 'groupshopping/edit.html'
    serializer_class = GroupShoppingSerializer

    def get_context_data(self, **kwargs):
        kwargs['secure'] = self.request.is_secure()
        kwargs['groupshopping'] = get_obj(GroupShopping, id=self.request.GET.get('id'))
        kwargs['musics'] = MusicInfo.objects.filter(status=MusicInfo.STATUS_VALID)
        return super(GroupShoppingEditView, self).get_context_data(**kwargs)

    def post(self, request, *args, **kwargs):
        groupshopping = get_obj(GroupShopping, id=request.POST.get('id'))
        serializer = GroupShoppingSerializer(groupshopping, data=request.POST)
        if serializer.is_valid():
            groupshopping = serializer.save(status=GroupShopping.STATUS_VALID)
            # 把之前的model全部删除，
            ShoppingModel.objects.filter(info=groupshopping).delete()
            # 统一重新创建
            shopping_models = json.loads(request.POST['models'])
            models_serializer = ShoppingModelSerializer(data=shopping_models, many=True)
            if models_serializer.is_valid():
                models_serializer.save(info_id=groupshopping.id, status=ShoppingModel.STATUS_VALID)
            return JsonResponse({'status': 0, 'detail': 'success'})
        else:
            return JsonResponse({'status': 1, 'detail': serializer.errors, 'errors': serializer.errors})


class GroupShoppingShelveView(AuthShopAPIView):
    def post(self, request, *args, **kwargs):
        if not {'title', 'id'}.issubset(request.data):
            return Response({'status': 1, 'detail': '参数错误'})
        groupshopping = get_obj(GroupShopping, id=request.data.get('id'), status=GroupShopping.STATUS_VALID)
        if not groupshopping:
            return Response({'status': 1, 'detail': '活动不存在！'})
        groupshopping.shelve = not groupshopping.shelve
        groupshopping.save()
        return Response({'status': 0, 'detail': 'success'})


class GroupShoppingDeleteView(AuthShopAPIView):
    def post(self, request, *args, **kwargs):
        """
        活动删除API
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        if not {'items'}.issubset(request.data):
            return Response({'status': 1, 'detail': '参数错误'})
        id_list = request.data.get("items").split(',')
        groupshopping_list = GroupShopping.objects.filter(status=GroupShopping.STATUS_VALID, id__in=id_list)
        if not groupshopping_list:
            return Response({'status': 1, 'detail': '活动列表不存在！'})
        for groupshopping in groupshopping_list:
            groupshopping.status = GroupShopping.STATUS_INVALID
            groupshopping.save()
        return Response({'status': 0, 'detail': 'success'})


class GroupShoppingJoinView(AuthMobileTemplateView):
    template_name = 'groupshopping/common_view.html'

    def get_context_data(self, **kwargs):
        kwargs['groupshopping'] = self.groupshopping
        kwargs['state'] = self.request.GET.get('state', '')
        kwargs['artical_color'] = '#e20e35'  # 测试主题
        return super(GroupShoppingJoinView, self).get_context_data(**kwargs)

    def get(self, request, *args, **kwargs):
        self.groupshopping = get_obj(GroupShopping, id=kwargs['product_id'], status=GroupShopping.STATUS_VALID)
        if not self.groupshopping:
            return render(request, 'mobile/message.html', {'message': '活动不存在，请退出重试！'})
        if not self.groupshopping.shelve:
            return render(request, 'mobile/message.html', {'message': '活动未上架！'})
        joined_member = get_obj(
            ShoppingMem,
            info=self.groupshopping,
            group__group_state__in=[ShoppingGroup.GROUP_DOING, ShoppingGroup.GROUP_SUCCESS],
            group__status=ShoppingGroup.STATUS_VALID,
            status=ShoppingMem.STATUS_VALID,
            user=request.user
        )
        if joined_member:
            url = '%s?shop=%s' % (reverse('groupshopping:shopping_group', args=[joined_member.group_id]), self.shop.id)
            return HttpResponseRedirect(url)
        return super(GroupShoppingJoinView, self).get(self, request, *args, **kwargs)

    @method_decorator(decorator_exception)
    def post(self, request, *args, **kwargs):
        return JsonResponse({'status': 0, 'detail': ''})


class GroupShoppingGroupView(AuthMobileTemplateView):
    template_name = 'groupshopping/group_master_view.html'

    def get_context_data(self, **kwargs):
        kwargs['shoppinggroup'] = self.shoppinggroup
        kwargs['has_join'] = ShoppingMem.objects.filter(
            info=self.shoppinggroup.info,
            group__group_state__in=[ShoppingGroup.GROUP_DOING, ShoppingGroup.GROUP_SUCCESS],
            group__status=ShoppingGroup.STATUS_VALID,
            status=ShoppingMem.STATUS_VALID
        ).filter(user=self.request.user).exists()
        return super(GroupShoppingGroupView, self).get_context_data(**kwargs)

    def get(self, request, *args, **kwargs):
        self.shoppinggroup = get_obj(ShoppingGroup, id=kwargs['group_id'], status=ShoppingGroup.STATUS_VALID)
        if not self.shoppinggroup:
            return render(request, 'mobile/message.html', {'message': '团组不存在，请退出重试！'})
        if not self.shoppinggroup.info.shelve:
            return render(request, 'mobile/message.html', {'message': '活动未上架！'})
        return super(GroupShoppingGroupView, self).get(self, request, *args, **kwargs)


class GroupShoppingMobileListView(AuthMobileTemplateView):
    template_name = 'groupshopping/mobile_list.html'

    def get_context_data(self, **kwargs):
        kwargs['groupshopping_list'] = GroupShopping.objects.filter(status=GroupShopping.STATUS_VALID, shelve=True,
                                                                    shop=self.shop)
        return super(GroupShoppingMobileListView, self).get_context_data(**kwargs)


class GroupShoppingPayingNumberView(APIView):
    permission_classes = (IsAuthenticated,)

    def post(self, request, *args, **kwargs):
        if not {'group_id'}.issubset(request.data):
            return Response({'status': 1, 'detail': '参数错误'})

        data = request.data
        group_id = data.get('group_id', '')
        group = get_obj(ShoppingGroup, id=group_id, status=ShoppingGroup.STATUS_VALID)
        if not group:
            return Response({'status': 1, 'detail': '团组不存在'})
        group.decrease_paying_number()

        return Response({'status': 0, 'detail': 'success'})
